package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 查询列表
     *
     * @param dto
     * @return
     */
    @GlobalTransactional(timeoutMills = 100000,rollbackFor = Exception.class) //RunningTimeException.class
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //1。参数检查
        dto.checkParam();
        //2。分装查询条件
        //2。1分页条件
        Page<ApUserRealname> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //2。2查询条件
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> pageRequest = page(pageReq, wrapper);
        //3。返回结果

        return new PageResponseResult(dto.getPage(), dto.getSize(), pageRequest.getTotal(), pageRequest.getRecords());
    }


    /**
     * 审核
     *
     * @param dto
     * @param status  2 审核失败   9 审核成功
     * @return
     */
    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {

//1。参数校验
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名认证的id不存在");
        }

//1.1。更具id查询ap_user_realname
        ApUserRealname realnameInfo = getById(dto.getId());
        if (realnameInfo == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证的信息不存在");
        }

        if (!AdminConstants.WAIT_AUTH.equals(realnameInfo.getStatus())) {//如果不是1，说明不是待审核状态
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "实名认证信息不是待审核状态");
        }
        //1.2更具ap_user_realname中关联的userId查询ap_user
        ApUser apUser = apUserMapper.selectById(realnameInfo.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证的信息不存在");
        }

        //2.修改ap_user_realname表的status状态  9

        realnameInfo.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            realnameInfo.setReason(dto.getMsg());

        }
        updateById(realnameInfo);//改实名认证状态


        //2.1 状态为9 帐号开通  直接返回
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //创建自媒体账户
            WmUser wmUser = createWmUser(apUser);
            //创建作者信息
            createApAuthor(wmUser);
        }
//5。更新用户状态
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
//返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Autowired
    private WemediaFeign wemediaFeign;

    //3。1开通自媒体账户信息
   private WmUser createWmUser(ApUser apUser) {
//1。用feign更具用户名查询wmUser是否创建
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());

        //2。如果已经创建  ，抛异常数据存在
        if (wmUserResult != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }

//3。创建wmUser信息，保存
        WmUser wmUser = new WmUser();

        wmUser.setApUserId(apUser.getId());//用户id
        wmUser.setName(apUser.getName());//用户名
        wmUser.setPassword(apUser.getPassword());//密码
        wmUser.setSalt(apUser.getSalt());//盐
        wmUser.setNickname(apUser.getName());//昵称
        wmUser.setImage(apUser.getImage());//头像
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);

        wmUser.setCreatedTime(new Date());

        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (saveResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, saveResult.getErrorMessage());
        }
        return saveResult.getData();
    }

    @Autowired
    private ArticleFeign articleFeign;

    //3。2创建作者信息
   private void createApAuthor(WmUser wmUser) {
        //1.检查是否成功调用
        ResponseResult<ApAuthor> apAuthorResponseResult = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthorResponseResult.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, apAuthorResponseResult.getErrorMessage());
        }
        //2。检查作者信息是否存在
        ApAuthor apAuthor = apAuthorResponseResult.getData();


//3。添加作者信息
        if (apAuthor != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "用户信息已存在");
        }
        apAuthor = new ApAuthor();

        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2);//平台自媒体人
        apAuthor.setUserId(wmUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult result = articleFeign.save(apAuthor);
        //4。结果失败，抛出异常
        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, result.getErrorMessage());
        }
    }
}
